package ant.parser;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import ant.io.LocationFile;
import ant.network.RequestHelper;
import ant.tools.PrintOut;

/**
 * XML解析类，实现接口{@link Parsers}类 <br/>
 * {@link #parseNetworkData(String, ParseInterface)} 根据字符串解析XML数据 <br/>
 * {@link #parseCacheData(ParseInterface)} 解析本地缓存数据 <br/>
 * 
 * @author 蒋豪
 * 
 */
public class XMLParser implements Parsers {

	/**
	 * 根据字符串解析XML数据
	 * 
	 * @param string
	 *            服务端返回的字符串
	 * @param object
	 *            解析字符串的类
	 * @return 解析完成的类
	 * @throws SAXException
	 */

	@Override
	public Object parseNetworkData(String string, RequestHelper cacheOperate) {

		Object object = cacheOperate.getParserObject();

		/* 将字符串转换成二进制 */
		byte[] bs = string.getBytes();
		ByteArrayInputStream inputStream = new ByteArrayInputStream(bs);
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parse = null;
		
			try {
				parse = factory.newSAXParser();
				XMLReader reader = parse.getXMLReader();
				reader.setContentHandler((ContentHandler) object);

				/* 转换数据流开始解析 */
				InputStreamReader isr = new InputStreamReader(inputStream);
				InputSource iSource = new InputSource(isr);
				reader.parse(iSource);

				/* 关闭流 */
				isr.close();
				inputStream.close();
				
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
				PrintOut.error("Freamwork ParserConfigurationException", "解析配置异常");
			} catch (IOException e) {
				e.printStackTrace();
				PrintOut.error("Freamwork IOException", "操作IO流出现异常");
			} catch (SAXException e) {
				e.printStackTrace();
				PrintOut.error("Freamwork SAXException", "解析XML出现异常");
			}
		
		return object;
	}

	/**
	 * 解析本地缓存数据
	 * 
	 * @return 返回解析完成的对象
	 * @throws SAXException
	 * @throws FileNotFoundException 
	 */
	@Override
	public Object parseCacheData(RequestHelper cacheOperate)
			{
		LocationFile locationFile=new LocationFile();
		InputStreamReader streamReader = null;
		Object object = null;
		try {
			streamReader = locationFile.getStreamReader(cacheOperate.getPath());
			String streamToString = locationFile.streamToString(streamReader);
			object = parseNetworkData(streamToString, cacheOperate);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			PrintOut.error("Freamwork FileNotFoundException", "找不到相应的文件");
		} catch (IOException e) {
			e.printStackTrace();
			PrintOut.error("Freamwork IOException", "操作IO流出现异常");
		}
		
		return object;
	}

}
